import {CodeJar} from '../3rd/codejar/codejar.js'
import * as Highlighter from './highlighter.js'
import {TypeCheck, Utils, EventListenerCollection} from './common.js'
import D from "./delegator.js"

export default class TextareaWithHighlight {
    constructor(editableElement, lang, text, placeholder) {
        this._ui = editableElement ?? Utils.CreateHTMLElement(`<div></div>`);
        D(this._ui).AddAttribute("placeholder", placeholder ?? "click to input ...");
        this._highlightLanguage = 'plaintext';
        this._ui.textContent = text ?? '';
        this._codejar = CodeJar(this._ui, editor => {
            editor.innerHTML = Highlighter.Highlight(editor.textContent, this._highlightLanguage);
        });
        this.SetLanguage(lang);
    }
    get element() {return this._ui;}

    SetLanguage(lang) {
        if (TypeCheck.IsString(lang)) {
            if (lang === this._highlightLanguage) return false;

            Highlighter.LoadLanguage(lang)
                .then(() => {
                    this._highlightLanguage = lang;
                    this._codejar.updateCode(this._ui.textContent);
                });
            return true;
        } return false;
    }

    SetText(str) {
        if (TypeCheck.IsString(str)) {
            this._codejar.updateCode(str);
            return true;
        }
        return false;
    }

    GetText() {
        return this._ui.textContent;
    }

    SetUpdateCallback(cbFn) {
        if(TypeCheck.IsFunction(cbFn)) {
            this._codejar.onUpdate(cbFn);
        }
    }

    Destroy() {
        this._codejar.destroy();
        this._codejar = undefined;
        this._updateCallBack = undefined;
    }
}

